package com.meowcook.controller;

import com.meowcook.common.AppResult;
import com.meowcook.exception.FileUploadException;
import com.meowcook.utils.COSClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 28792
 * Date: 2025-05-25
 * Time: 18:46
 */
@Slf4j
@Api(tags = "图片操作接口")
@RestController
@RequestMapping("/image")
public class ImageController {

    @ApiOperation("图片上传")
    @PostMapping("/upload")
    public AppResult<String> upload(@ApiParam("file") MultipartFile file,
                                    @ApiParam("type") @NotBlank String type) {
        if (file == null) {
            return AppResult.fail("上传文件为空");
        }
        log.info("上传文件类型: {}", type);
        String folder = null;
        if (type.equals("cooking")) {
            folder = "cooking_image";
        } else if (type.equals("recipe")) {
            folder = "recipe_image";
        } else if (type.equals("user")) {
            folder = "user_image";
        } else {
            return AppResult.fail("上传文件类型错误");
        }
        try {
            String cookingImageUrl = COSClientUtils.uploadFile(file, folder);
            return AppResult.success("上传成功", cookingImageUrl);
        } catch (InterruptedException e) {
            throw new FileUploadException("上传文件中断!");
        }
    }

    @ApiOperation("图片删除")
    @PostMapping("/delete")
    public AppResult delete(@ApiParam("path") @NotBlank String path) {
        log.info("删除文件路径: {}", path);
        COSClientUtils.deleteFile(path);
        return AppResult.success("删除成功");
    }
}
